package bigdata.controller;

import bigdata.pojo.Permission;
import bigdata.pojo.User;
import bigdata.service.UserService;
import bigdata.util.Constants;
import bigdata.util.RedisUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
//	@Autowired
	@Reference(check = false)
    UserService userService;
	
//	@Autowired
//	RoleMapper roleMapper;

	@Autowired
    RedisUtil redisUtil;

	@RequestMapping("jsp/logout.do")
	public String logout(HttpSession session){
		session.removeAttribute(Constants.USER_SESSION);
		return "redirect:/login";
	}
	
	@RequestMapping("login")
	public String login(){
		return "login";
	}
	
	@RequestMapping("jsp/frame")
	public String frame(HttpSession session){
		if(session.getAttribute(Constants.USER_SESSION)==null){
			return "redirect:/login";
		}
		User user = (User)session.getAttribute(Constants.USER_SESSION);
		/*
		List<Permission> permList = roleMapper.getPermissionByRoleId(user.getUserRole());
		//1、权限菜单放到 session，相比 model 不需要每个请求都要重新取一次；2、性能
		//3、改进：如果没有菜单权限，但知道菜单的地址，能不能访问？判断 session 是否为空，同时判断请求 URL
		//4、改进：缓存从用户级别扩展到全局级别 cache.put(角色代码，角色对应所有菜单)

		*/
		List<Permission> permList = (List<Permission>) redisUtil.getObj("perm_" + user.getUserRole());
		if (permList == null) {
//			permList = roleMapper.getPermissionByRoleId(user.getUserRole());
			redisUtil.setObj("perm_" + user.getUserRole(), permList);
		}
		session.setAttribute("permList", permList);
		return "jsp/frame";
	}
	
	@RequestMapping("login.do")
	public String logindo(String userCode, String userPassword,
			HttpSession session,
			Model model){
		User user = userService.getUser(userCode);
		if(user == null){
			model.addAttribute("error", "用户不存在");
		}else if(!user.getUserPassword().equals(userPassword)){
			model.addAttribute("error", "密码不对");
		}else{
			session.setAttribute(Constants.USER_SESSION, user);
			return "redirect:/jsp/frame";
		}
		return "login";
	}
	
	@GetMapping("jsp/checkuser")
	@ResponseBody
	public String checkuser(String userCode) {
		User user = userService.getUser(userCode);
		if(user == null) {
			return "该用户可以使用";
		} else {
			return "该用户名已经被使用";
		}
	}
	
	@PostMapping("ajaxLogin.do")
	@ResponseBody
	public Map<String,Object> doAJAXLogin(String userCode, String userPassword, HttpSession session) {
		Map<String,Object> json = new HashMap<String, Object>();
		User user = userService.getUser(userCode);
		if(user == null || !user.getUserPassword().equals(userPassword)) {
			json.put("success","");
		}else{
			session.setAttribute(Constants.USER_SESSION, user);
			json.put("success","true");
		}
		return json;
	}

	@Autowired
	private DefaultKaptcha captchaProducer;
	/**
	 * 获取验证码的请求路径
	 *
	 * @param request 请求
	 * @param response 响应
	 */
	@RequestMapping("/defaultKaptcha")
	public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception{
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			//生产验证码字符串并保存到session中
			String createText = captchaProducer.createText();
			request.getSession().setAttribute("verifyCode", createText);
			//使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = captchaProducer.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			response.sendError(HttpServletResponse.SC_NOT_FOUND);
			return;
		}

		//定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		response.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = response.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}
}
